package cn.crex1.xiaomi.core.orm.datasource;
 
import java.sql.Connection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.crex1.xiaomi.core.orm.ConfigbleJdbcDataSource;
import cn.crex1.xiaomi.core.orm.druid.DruidCocfig;
import cn.crex1.xiaomi.core.orm.transaction.TransactionManager;
import cn.crex1.xiaomi.core.orm.transaction.support.JdbcTransactionManager;

public class JdbcDataSource implements ConfigbleJdbcDataSource {
	private TransactionManager transactionManager;
	
	private DruidCocfig druidCocfig;
	
	private Logger logger=LoggerFactory.getLogger(JdbcDataSource.class);
	
	//获取数据源配置对象和事务管理器
	public JdbcDataSource() {
		transactionManager=new JdbcTransactionManager();
		druidCocfig=new DruidCocfig();
	}
	
	/**
	 * 打开数据源包裹事务
	 */
	@Override
	public Connection openDataSource() {
		Connection openConn = druidCocfig.openConn();	
		System.out.println(openConn);
		if (openConn!=null) {
			logger.debug("open a transaction");
			transactionManager.openTransaction(openConn);
			return openConn;
		}
		return null;
		
	}
	/**
	 * 关闭数据源关闭事务
	 */
	@Override
	public void closeDataSource() {
		Connection connection = druidCocfig.getCurrentConn().get();
		if (connection!=null) {
			logger.debug("close a transaction");
			transactionManager.closeTransaction(connection);
//			druidCocfig.closeConnection(connection);
		}
	}
	/**
	 * 事务提交与回滚
	 */
	@Override
	public void manaedTransaction() {
		Connection connection = druidCocfig.getCurrentConn().get();
		if (connection!=null) {
			logger.debug("commit a transaction");
			transactionManager.commitTransaction(connection);
			closeDataSource();
		}
	}
	/**
	 * 返回事务管理器
	 * @return
	 */
	public TransactionManager getTransactionManager() {
		return transactionManager;
	}

}
